<template>
  <div class="dashboard-container">
    <!-- 顶部欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <h2>欢迎回来，{{ userInfo.realName || userInfo.username }}！</h2>
        <p>今天是 {{ currentDate }}，祝您身体健康！</p>
      </div>
      <div class="user-avatar">
        <el-avatar :size="80" :src="userInfo.avatar || '/imgs/default-avatar.png'" />
      </div>
    </div>


    <!-- 用户基本信息卡片 -->
    <el-card class="user-info-card" shadow="hover">
      <div class="user-info">
        <el-avatar :size="80" :src="userInfo.avatar" />
        <div class="user-details">
          <h3>{{ userInfo.realName || userInfo.username }}</h3>
          <p><span class="label">性别:</span> {{ userInfo.gender === 'male' ? '男' : userInfo.gender === 'female' ? '女' : '未知' }}</p>
          <p><span class="label">生日:</span> {{ formatDate(userInfo.birthday) }}</p>
          <p><span class="label">手机号:</span> {{ userInfo.phone }}</p>
          <p><span class="label">邮箱:</span> {{ userInfo.email }}</p>
        </div>
      </div>
    </el-card>

    <div class="stats-container">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card shadow="hover">
            <div class="stat-card">
              <h3>我的预约</h3>
              <p class="stat-value">{{ appointmentCount }}</p>
              <el-button type="primary" @click="router.push('/user/appointments')">查看详情</el-button>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <div class="stat-card">
              <h3>我的收藏</h3>
              <p class="stat-value">{{ favoriteCount }}</p>
              <el-button type="primary" @click="router.push('/user/favorites')">查看详情</el-button>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <div class="stat-card">
              <h3>我的评价</h3>
              <p class="stat-value">{{ reviewCount }}</p>
              <el-button type="primary" @click="router.push('/user/reviews')">查看详情</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from "axios";
import dayjs from 'dayjs';

const router = useRouter();
const userInfo = ref({});
const appointmentCount = ref(0);
const favoriteCount = ref(0);
const reviewCount = ref(0);
const recentAppointments = ref([]);

const currentDate = ref('')
const updateCurrentDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth() + 1
  const day = now.getDate()
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const weekday = weekdays[now.getDay()]

  currentDate.value = `${year}年${month}月${day}日 ${weekday}`
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '未设置';
  if (typeof date === 'number' || /^\d+$/.test(date)) {
    return dayjs(parseInt(date)).format('YYYY-MM-DD');
  }
  return dayjs(date).format('YYYY-MM-DD');
};

// 获取统计数据
const fetchStatistics = async (userId) => {
  try {
    const [appointmentRes, favoriteRes, reviewRes] = await Promise.all([
      axios.get(`${BASE_URL}/v1/user/countsAppointment`, {
        params: { userId },
        withCredentials: true
      }),
      axios.get(`${BASE_URL}/v1/user/countsFavorite`, {
        params: { userId },
        withCredentials: true
      }),
      axios.get(`${BASE_URL}/v1/user/countsReview`, {
        params: { userId },
        withCredentials: true
      })
    ]);

    if (appointmentRes.data?.state === 2000) {
      appointmentCount.value = appointmentRes.data.data;
      localStorage.setItem('appointmentCount', appointmentRes.data.data);
    }
    if (favoriteRes.data?.state === 2000) {
      favoriteCount.value = favoriteRes.data.data;
      localStorage.setItem('favoriteCount', favoriteRes.data.data);
    }
    if (reviewRes.data?.state === 2000) {
      reviewCount.value = reviewRes.data.data;
      localStorage.setItem('reviewCount', reviewRes.data.data);
    }
  } catch (error) {
    console.error("获取统计数据出错:", error);
  }
};

// 获取用户信息和统计数据
const fetchUserData = async () => {
  try {
    const userResponse = await axios.get(`${BASE_URL}/v1/user/info`, {
      withCredentials: true
    });

    if (userResponse.data?.state === 2000) {
      userInfo.value = userResponse.data.data;
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
      await fetchStatistics(userInfo.value.id);
    }
  } catch (error) {
    console.error("获取用户数据出错:", error);
    if (error.response?.status === 401) {
      router.push('/login');
    }
  }
};

onMounted(() => {
  // 从本地存储初始化所有数据
  userInfo.value = JSON.parse(localStorage.getItem('userInfo')) || {};
  appointmentCount.value = parseInt(localStorage.getItem('appointmentCount')) || 0;
  favoriteCount.value = parseInt(localStorage.getItem('favoriteCount')) || 0;
  reviewCount.value = parseInt(localStorage.getItem('reviewCount')) || 0;

  updateCurrentDate();
  // 获取最新数据
  fetchUserData();
});
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.user-info-card {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-details {
  flex: 1;
}

.user-details h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
}

.user-details p {
  margin: 5px 0;
  color: #666;
}

.user-details .label {
  display: inline-block;
  width: 60px;
  color: #333;
  font-weight: bold;
}

.stats-container {
  margin: 20px 0;
}

.stat-card {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}

.recent-activities {
  margin-top: 20px;
}

/* 欢迎区域 */
.welcome-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #e3f2fd, #bbdefb);
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.welcome-content h2 {
  font-size: 24px;
  color: #2c3e50;
  margin-bottom: 10px;
}

.welcome-content p {
  color: #555;
  font-size: 16px;
}

.user-avatar {
  display: flex;
  align-items: center;
}

</style>